import { DatePicker } from '@/components/AntdProxy';
import Crud from '@/components/Crud';
import { LineSelect } from '@/components/CustomForm';
import useMaterial from '@/hooks/useMaterial';
import request from '@/utils/request';
import { CopyOutlined, DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Modal, Space, message } from 'antd';
import dayjs from 'dayjs';
import { useRef, useState } from 'react';
import Copy from './components/Copy';
import Detail from './components/Detail';
import Save, { AUTO_TRIP_OPTIONS } from './components/Save';

const getList = async (params) => {
  const res = await request({
    url: '/datas/line/plan/list',
    method: 'GET',
    custom: true,
    params: {
      ...params,
      fromTime: params.fromTime
        ? dayjs(params.fromTime).format('YYYY-MM-DD')
        : '',
      toTime: params.toTime ? dayjs(params.toTime).format('YYYY-MM-DD') : '',
    },
  });
  return {
    total: res?.total,
    data: res?.data,
  };
};

const Index = () => {
  const [mode, setMode] = useState('list');
  const [record, setRecord] = useState();
  const [selectedRows, setSelectedRows] = useState([]);
  const crudRef = useRef();
  const { materialTypeMap } = useMaterial();

  const deleteRow = (id) => {
    const ids = id ? [id] : selectedRows?.map?.((item) => item.linePlanId);
    Modal.confirm({
      title: `确认删除所选数据?`,
      onOk: async () => {
        await request({
          url: '/datas/line/plan/delete',
          method: 'POST',
          data: { ids },
        });
        message.success('操作成功');
        crudRef.current?.reload();
        setSelectedRows([]);
      },
    });
  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '线路',
      dataIndex: 'lineName',
      fixed: 'left',
      width: 280,
    },
    {
      title: '物料类型',
      dataIndex: 'type',
      width: 90,
      render: (text) => materialTypeMap[text],
    },
    {
      title: '日期',
      dataIndex: 'day',
      width: 120,
      render: (text) => (text ? dayjs(text).format('YYYY-MM-DD') : ''),
    },
    {
      title: '计划车数',
      dataIndex: 'total',
      width: 90,
    },
    {
      title: '计划编号',
      dataIndex: 'planCode',
      width: 180,
    },
    {
      title: '客户业务',
      dataIndex: 'fixed',
      width: 90,
      render: (text) => (text === 0 ? '是' : '否'),
    },
    {
      title: '自动派单',
      dataIndex: 'autoTrip',
      width: 90,
      render: (text) =>
        AUTO_TRIP_OPTIONS?.find((item) => item.value === text)?.label,
    },
    {
      title: '级别',
      dataIndex: 'level',
      width: 90,
      render: (text) => (text === 0 ? '优秀' : '普通'),
    },
    {
      title: '优先派单',
      dataIndex: 'firstTrip',
      width: 90,
      render: (text) => (text === 0 ? '否' : '是'),
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: 120,
    },
    {
      title: '系统时间',
      dataIndex: 'time',
      width: 180,
      render: (text) => (text ? dayjs(text).format('YYYY-MM-DD HH:mm:ss') : ''),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 140,
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'operate',
      fixed: 'right',
      width: 140,
      render: (text, record) => {
        return (
          <Space>
            <a
              onClick={() => {
                setRecord(record);
                setMode('detail');
              }}
            >
              详情
            </a>
            <a
              onClick={() => {
                setRecord(record);
                setMode('edit');
              }}
            >
              编辑
            </a>
            <a
              onClick={() => {
                deleteRow(record.linePlanId);
              }}
            >
              删除
            </a>
          </Space>
        );
      },
    },
  ];

  const fields = [
    {
      label: '线路',
      name: 'lineId',
      children: <LineSelect />,
    },
    {
      label: '开始日期',
      name: 'fromTime',
      children: <DatePicker placeholder="请选择开始日期" allowClear={false} />,
    },
    {
      label: '结束日期',
      name: 'toTime',
      children: <DatePicker placeholder="请选择结束日期" allowClear={false} />,
    },
  ];

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="linePlanId"
        queryFormProps={{
          labelCol: 7,
          initialValues: {
            fromTime: dayjs(),
            toTime: dayjs().add(1, 'day'),
          },
        }}
        fields={fields}
        columns={columns}
        request={getList}
        toolbar={
          <>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setMode('create')}
            >
              新增
            </Button>
            <Button
              icon={<CopyOutlined />}
              onClick={() => setMode('copy')}
              disabled={selectedRows.length === 0}
            >
              复制
            </Button>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedRows.length === 0}
              onClick={() => deleteRow()}
            >
              批量删除
            </Button>
          </>
        }
        tableProps={{
          rowSelection: {
            selectedRowKeys: selectedRows?.map?.((item) => item.linePlanId),
            onChange: (_, _selectedRows) => {
              setSelectedRows(_selectedRows);
            },
          },
        }}
      />
      <Save
        open={mode === 'create' || mode === 'edit'}
        record={record}
        onCancel={() => {
          setRecord();
          setMode('list');
        }}
        onOk={() => {
          setRecord();
          setMode('list');
          crudRef.current?.reload();
        }}
      />
      <Detail
        open={mode === 'detail'}
        record={record}
        onCancel={() => {
          setRecord();
          setMode('list');
        }}
      />
      <Copy
        open={mode === 'copy'}
        records={selectedRows}
        onCancel={() => {
          setMode('list');
        }}
        onOk={() => {
          setMode('list');
          setSelectedRows([]);
          crudRef.current?.reload();
        }}
      />
    </>
  );
};

export default Index;
